import Vue from 'vue'
import Vuex from 'vuex'
import {
    getToken,
    setToken,
    removeToken,
} from '@/utils/auth'
import { login, loginByEmail, logout } from "@/api/member/login";
import { getMemberInfo } from '@/api/member/member';
Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
        token: getToken(),
        user: null,
        login: '0'
    },
    mutations: {
        /* 设置token */
        set_token(state, token) {
            state.token = token
        },
        /* 设置用户信息 */
        set_user(state, user) {
            state.user = user
        },
        /* 设置登录状态 */
        set_login(state, login) {
            state.login = login
        }
    },
    actions: {
        /* 用户登录 */
        login({ commit }, userInfo) {
            return new Promise((resolve, reject) => {
                login(userInfo).then(res => {
                    const access_token = res.data.access_token
                    commit("set_token", access_token)
                    setToken(access_token)
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        /* 用户邮箱验证码登录 */
        loginByEmail({ commit }, userInfo) {
            console.log(userInfo)
            return new Promise((resolve, reject) => {
                loginByEmail(userInfo).then(res => {
                    const access_token = res.data.access_token
                    commit("set_token", access_token)
                    setToken(access_token)
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        /* 获取用户信息 */
        getMemberInfo({ commit }) {
            return new Promise((resolve, reject) => {
                getMemberInfo().then(res => {
                    commit('set_user', res.data)
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        /* 退出登录 */
        logout({ commit, state }) {
            return new Promise((resolve, reject) => {
                logout().then(() => {
                    commit('set_user', null)
                    commit('set_token', '')
                    removeToken()
                    resolve()
                })
            })
        },

        // 前端 登出
        fedLogOut({ commit }) {
            return new Promise(resolve => {
                commit('set_user', null)
                commit('set_token', '')
                removeToken()
                resolve()
            })
        }
    },
    getters: {
        token: (state) => state.token,
        user: (state) => state.user,
        login: (state) => state.login
    }
})

export default store
